<template>
  <lay-layer
    v-model="visible"
    :title="dialogTitle"
    :area="['650px', '650px']"
    :maxmin="true"
    :resize="true"
    @close="handleClose"
  >
    <div class="address-dialog-content">
      <lay-form
        :model="formData"
        :rules="formRules"
        ref="formRef"
        :disabled="mode === 'view'"
        label-width="100px"
      >
        <lay-form-item label="用户ID" :prop="mode === 'create' ? 'userId' : ''">
          <lay-input 
            v-model="formData.userId" 
            placeholder="请输入用户ID" 
            :readonly="mode !== 'create'"
          />
        </lay-form-item>

        <lay-form-item label="收货人" prop="receiverName">
          <lay-input v-model="formData.receiverName" placeholder="请输入收货人姓名" />
        </lay-form-item>

        <lay-form-item label="手机号" prop="receiverPhone">
          <lay-input v-model="formData.receiverPhone" placeholder="请输入手机号" />
        </lay-form-item>

        <lay-form-item label="省份" prop="province">
          <lay-input v-model="formData.province" placeholder="请输入省份" />
        </lay-form-item>
        <lay-form-item label="城市" prop="city">
          <lay-input v-model="formData.city" placeholder="请输入城市" />
        </lay-form-item>
        <lay-form-item label="区县" prop="district">
          <lay-input v-model="formData.district" placeholder="请输入区县" />
        </lay-form-item>

        <lay-form-item label="邮政编码" prop="postalCode">
          <lay-input v-model="formData.postalCode" placeholder="请输入邮政编码" />
        </lay-form-item>

        <lay-form-item label="详细地址" prop="address">
          <lay-textarea 
            v-model="formData.address" 
            placeholder="请输入详细地址"
            :rows="3"
          />
        </lay-form-item>

        <lay-form-item label="设为默认" prop="isDefault">
          <lay-switch 
            :model-value="formData.isDefault === 1" 
            @update:model-value="(value) => formData.isDefault = value ? 1 : 0"
            :switch-text="['是', '否']"
          />
        </lay-form-item>
      </lay-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <lay-button @click="handleClose">取消</lay-button>
        <lay-button 
          v-if="mode !== 'view'" 
          type="primary" 
          @click="handleSubmit"
          :loading="submitting"
        >
          {{ mode === 'create' ? '创建' : '更新' }}
        </lay-button>
      </div>
    </template>
  </lay-layer>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { layer } from '@layui/layui-vue'
import { UserApi } from '../../../api/module/user'
import type { UserAddress } from '../../../types/user'

// Props
interface Props {
  modelValue: boolean
  mode: 'view' | 'create' | 'edit'
  addressData?: UserAddress | null
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  mode: 'view',
  addressData: null
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'success': []
}>()

// 响应式数据
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const submitting = ref(false)
const formRef = ref()

// 对话框标题
const dialogTitle = computed(() => {
  switch (props.mode) {
    case 'view':
      return '查看地址'
    case 'create':
      return '新增地址'
    case 'edit':
      return '编辑地址'
    default:
      return '地址信息'
  }
})

// 表单数据
const formData = reactive<Partial<UserAddress>>({
  userId: 0,
  receiverName: '',
  receiverPhone: '',
  province: '',
  city: '',
  district: '',
  address: '',
  postalCode: '',
  isDefault: 0
})

// 表单验证规则
const formRules = {
  userId: [
    { required: true, message: '请输入用户ID', trigger: 'blur' }
  ],
  receiverName: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '收货人姓名长度在2-20个字符', trigger: 'blur' }
  ],
  receiverPhone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  province: [
    { required: true, message: '请输入省份', trigger: 'blur' }
  ],
  city: [
    { required: true, message: '请输入城市', trigger: 'blur' }
  ],
  district: [
    { required: true, message: '请输入区县', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { min: 5, max: 200, message: '详细地址长度在5-200个字符', trigger: 'blur' }
  ],
  postalCode: [
    { pattern: /^\d{6}$/, message: '请输入正确的邮政编码格式', trigger: 'blur' }
  ]
} as any

// 重置表单
const resetForm = () => {
  Object.keys(formData).forEach((key) => {
    if (key === 'isDefault' || key === 'userId') {
      (formData as any)[key] = 0
    } else {
      (formData as any)[key] = ''
    }
  })
  formRef.value?.clearValidate()
}

// 填充表单数据
const fillFormData = (data: UserAddress) => {
  Object.keys(formData).forEach((key) => {
    if (key in data) {
      (formData as any)[key] = (data as any)[key]
    }
  })
}

// 监听地址数据变化
watch(() => props.addressData, (newData) => {
  if (newData) {
    fillFormData(newData)
  } else {
    resetForm()
  }
}, { immediate: true })

// 监听模式变化
watch(() => props.mode, () => {
  if (props.mode === 'create') {
    resetForm()
  }
})

// 关闭对话框
const handleClose = () => {
  visible.value = false
  resetForm()
}

// 提交表单
const handleSubmit = async () => {
  try {
    // 表单验证
    const valid = await formRef.value?.validate()
    if (!valid) {
      return
    }

    submitting.value = true

    // 准备提交数据
    const submitData: any = {
      receiverName: formData.receiverName,
      receiverPhone: formData.receiverPhone,
      province: formData.province,
      city: formData.city,
      district: formData.district,
      address: formData.address,
      isDefault: formData.isDefault as 0 | 1
    }

    // 处理邮政编码 - 如果为空则不提交
    if (formData.postalCode && formData.postalCode.trim() !== '') {
      submitData.postalCode = formData.postalCode
    }

    const userId = Number(formData.userId)

    if (props.mode === 'create') {
      // 创建地址
      await UserApi.createUserAddress(userId, submitData)
      layer.msg('创建成功', { icon: 1 })
    } else if (props.mode === 'edit') {
      // 更新地址
      await UserApi.updateUserAddress(userId, props.addressData!.id!, submitData)
      layer.msg('更新成功', { icon: 1 })
    }

    emit('success')
    handleClose()
  } catch (error) {
    layer.msg('操作失败', { icon: 2 })
    console.error('提交失败:', error)
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.address-dialog-content {
  padding: 20px;
}

.address-dialog-content .lay-form-item {
  margin-bottom: 16px;
}

.address-dialog-content .lay-textarea {
  min-height: 80px;
}

.dialog-footer {
  text-align: right;
  padding: 10px 20px;
  border-top: 1px solid #e6e6e6;
}

.dialog-footer .lay-button {
  margin-left: 8px;
}
</style>